//
//  FYNetworkingManager.m
//  FYNetworking
//
//  Created by Felix Yin on 2017/5/5.
//  Copyright © 2017年 Felix Yin. All rights reserved.
//

#import "FYNetworkingManager.h"
#import "AFNetworking.h"
#import "FYNetworkingRequestStting.h"
#import "FYNetworkingRequestGenerator.h"

@interface FYNetworkingManager ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
@property (nonatomic, strong) NSMutableDictionary *cacheRequest;

@end

@implementation FYNetworkingManager


#pragma mark Operation Module

- (NSNumber *)sendRequest:(FYNetworkingFileRequestStting *)requestSetting{
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *sessionManager = self.sessionManager;
    NSURLRequest *request = [[FYNetworkingRequestGenerator shareInstance] request:requestSetting];
   __block NSURLSessionDataTask *task = [sessionManager dataTaskWithRequest:request uploadProgress:requestSetting.requestProgressCallBack downloadProgress:requestSetting.downLoadProgressCallBack completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        //移除请求缓存
        NSNumber *requestID = [NSNumber numberWithUnsignedInteger:task.hash];
        [weakSelf.cacheRequest removeObjectForKey:requestID];
        if(task.state == NSURLSessionTaskStateCanceling || ([error.localizedDescription isEqualToString:@"cancelled"])){
            NSLog(@"Task Cancelled");
        }else{
            if(error){
                if(requestSetting.requestCompleteCallBack){
                    requestSetting.requestCompleteCallBack(nil, error);
                }
            }else{
                if(requestSetting.requestCompleteCallBack){
                    //完成回调
                    requestSetting.requestCompleteCallBack(responseObject,nil);
                }
            }
        }
    }];
    [task resume];
    NSNumber *requestID = [NSNumber numberWithUnsignedInteger:task.hash];
    [self.cacheRequest setObject:task forKey:requestID];
    return requestID;
}

- (void)cancleRequest:(NSNumber *)requestID{
    if(requestID){
      NSURLSessionDataTask *task = (NSURLSessionDataTask *) [self.cacheRequest objectForKey:requestID];
        [task cancel];
        [self.cacheRequest removeObjectForKey:requestID];
    }
}

#pragma mark Initianlize

+(instancetype) shareInstance{
    static dispatch_once_t onceToken;
    static FYNetworkingManager *manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[FYNetworkingManager alloc] init];
    });
    return manager;
}


#pragma mark LazyLoading

- (AFURLSessionManager *)sessionManager{
    if (!_sessionManager) {
        NSUInteger memoryCapacity = 4 * 1024 * 1024;
        NSUInteger diskCapacity = 20 * 1024 * 1024;
        NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:nil];
        [NSURLCache setSharedURLCache:urlCache];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.timeoutIntervalForResource = 20;
        _sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil];
    }
    return _sessionManager;
}

- (NSMutableDictionary *)cacheRequest{
    if (!_cacheRequest) {
        _cacheRequest = [[NSMutableDictionary alloc] init];
    }
    return _cacheRequest;
}

@end
